package com.nulldev.util.web.nCaptcha.captchas.auto;

import java.io.InputStream;
import java.util.HashMap;

import com.nulldev.util.crypto.encryptAPI.XXTEA;
import com.nulldev.util.java.DataSet;
import com.nulldev.util.java.JVMUtil;
import com.nulldev.util.lang.json.Json;
import com.nulldev.util.lang.json.JsonObject;
import com.nulldev.util.lang.json.JsonValue;
import com.nulldev.util.uri.server.RequestType;
import com.nulldev.util.uri.server.v2.HttpPage2;
import com.nulldev.util.web.nCaptcha.backend.user.User;
import com.nulldev.util.web.nCaptcha.backend.user.UserManager;

public class AutoPayloadSubmission extends HttpPage2 {

	public AutoPayloadSubmission() {
		super("/ncaptcha/auto_upload");
	}

	@Override
	public DataSet<Integer, InputStream> request(RequestType type, String url, HashMap<String, String> headers,
			byte[] extraData, String ip) {
		final User user = UserManager.registerOrLoadUser(ip);
		final String data = XXTEA.decryptBase64StringToString(headers.get("data"), user.key());
		if (data == null) {
			return new DataSet<Integer, InputStream>(200, createStream("ERROR, DATA REJECTED."));
		}
		final JsonObject obj = Json.parse(data).asObject();
		obj.printlnf();
		double score = 0.6;
		String prevUA = "";
		for (final JsonValue s : obj.get("userAgents").asArray()) {
			if (prevUA.equals("")) {
				prevUA = s.asString();
				continue;
			}
			if (!prevUA.equals(s.asString())) {
				score -= 0.05;
			}
		}
		if (obj.getBoolean("sel") || obj.getBoolean("ele")) {
			score -= 0.6;
		}
		if (obj.getBoolean("navOK")) {
			score += 0.1;
		}
		if (obj.getBoolean("hasAntiAdBlock")) {
			score += 0.05;
		}
		if (obj.getBoolean("evalOK")) {
			score += 0.1;
		}
		if (obj.getString("storage", "").equals("found")) {
			score += 0.2;
		}else if (obj.getString("storage", "").equals("found, incognito")) {
			score += 0.1;
		}else if (obj.getString("storage", "").equals("sec block")) {
			score -= 0.05;
		}
		final JsonObject result = new JsonObject();
		result.add("passed", (score > 0.95));
		result.add("score", score);
		return new DataSet<Integer, InputStream>(200, createStream(result.toString()));
	}

}
